package com.mark.other.java8;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;

public class Stream {

    @Test
    public void test(){
        //数据准备start
        List<Map<String, Object>> list = Lists.newArrayList();
        Map<String, Object> map1 = Maps.newHashMap();
        map1.put("host", "192.1.1.206");
        map1.put("count", 25);
        map1.put("type", "A");

        Map<String, Object> map2 = Maps.newHashMap();
        map2.put("host", "192.1.1.207");
        map2.put("count", 25);
        map2.put("type", "A");

        Map<String, Object> map3 = Maps.newHashMap();
        map3.put("host", "192.1.1.205");
        map3.put("count", 25);
        map3.put("type", "A");

        Map<String, Object> map4 = Maps.newHashMap();
        map4.put("host", "192.1.1.205");
        map4.put("count", 5);
        map4.put("type", "A");

        list.add(map1);
        list.add(map2);
        list.add(map3);
        list.add(map4);
        //数据准备end

        //根据map中key进行分组，得到的collect的key为host字段值，value为host对应的map
        Map<String, List<Map<String, Object>>> collect = list
                .stream()
                .collect(Collectors.groupingBy(e -> e.get("host").toString()+e.get("type")));
        System.out.println(collect);

        Map<String, Object> result = Maps.newHashMap();
        //遍历collect将List<Map<String, Object>>中的count字段求和
        collect.forEach((key, valueList) -> {
            int count = valueList.stream().mapToInt(e -> (int) e.get("count")).sum();
            result.put(key, count);
        });
        System.out.println(result);
    }
}
